/*
//	CP2013 Traffic Simulator Assignment :: (MVC) Controller :: Database Access Class (Function Definitions)
//	Copyright (c) 2010, Adam Rehn
//
//	This file contains the function definitions for this component.
*/
#include "database.h"

dbAccess::dbAccess()
{
	//Set the database handle to null
	db = NULL;
}

dbAccess::dbAccess(char* path)
{
	dbAccess();
	open(path);
}

dbAccess::~dbAccess()
{
	close();
}

//Use these to open and close connections
bool dbAccess::open(char* path)
{
	//Attempt to open the database
	bool success = (sqlite3_open(path, &db) == SQLITE_OK);
	
	//If the database could not be opened, set the handle to null
	if (!success)
		db = NULL;
	
	//Return the result
	return success;
}

void dbAccess::close()
{
	//Only attempt to close the connection if it is already open
	if (is_open())
	{
		//Close the connection
		sqlite3_close(db);
		db = NULL;
	}
}

//Use this to check if a connection is currently open
bool dbAccess::is_open()
{
	return (db != NULL);
}

//Use this to insert data
bool dbAccess::insertData(string table, map<string,string> keysAndVals)
{
	//We cannot insert any data if there is no connection currently open
	if (!is_open())
		return false;
	
	//Prepare the SQL statement
	string sql = "INSERT INTO '" + table + "' (";
	
	//Loop through the keys
	for (map<string,string>::iterator keys = keysAndVals.begin(); keys != keysAndVals.end(); ++keys)
	{
		//Append each key
		sql += "'" + keys->first + "'";
		
		//Seperate the list with commas
		if (++keys != keysAndVals.end())
			sql += ", ";
		--keys;
	}
	
	//Continue preparing the SQL statement
	sql += ") VALUES (";
	
	//Loop through the values
	for (map<string,string>::iterator values = keysAndVals.begin(); values != keysAndVals.end(); ++values)
	{
		//Append each value
		sql += "'" + values->second + "'";
		
		//Seperate the list with commas
		if (++values != keysAndVals.end())
			sql += ", ";
		--values;
	}
	
	//Complete the SQL statement
	sql += ");";
	
	//Attempt to execute and return whether or not we are successful
	return (sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL) == SQLITE_OK);
}

simulationPersistentStorage::simulationPersistentStorage() : dbAccess()
{
	//Open the simulation's database file
	//open(DEFAULT_DATABASE_PATH);
	//if (!is_open())
	//	throw "Could not open the database!";
}

bool simulationPersistentStorage::insertResults(simulationParams setup, unsigned int numCarsPassedThroughIntersection)
{
	
}
